package com.acme.team03.net;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import com.acme.team03.messages.Message;
import com.acme.team03.net.server.ConnectionDispatcher;

public abstract class MessageHandler implements Runnable {
	private BlockingQueue<Message> msgQueue;
	private volatile boolean isStopped;
	protected ConnectionDispatcher connDispatcher;

	public MessageHandler(ConnectionDispatcher connDispatcher) {
		msgQueue = new LinkedBlockingQueue<Message>();
		this.connDispatcher = connDispatcher;
	}

	public void run() {
		while (!isStopped) {
			try {
				Message msg = msgQueue.take();
				processMessage(msg);
			} catch (InterruptedException e) {
				close();
			}
		}
	}

	public void close() {
		isStopped = true;
	}

	protected abstract void processMessage(Message msg);

	public void handleMessage(Message message) throws InterruptedException {
		msgQueue.put(message);
	}
}
